#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "unistd.h"
#include "sys/types.h"
#include "fcntl.h"
#include "poll.h"
#include "sys/select.h"
#include "sys/time.h"

#define KEY0VALUE  0xF0
#define INVAVALUE  0x00


int main(int argc, char *argv[])
{

    int fd,ret_val;
    unsigned char *filename;
    unsigned char keyvalue;
    struct pollfd fds;
    fd_set readfds;
    struct timeval timeout;
    if (argc != 3)
    {
        printf("Usage: ERROR\r\n");
        return -1;
    }
    
    filename = argv[1];

    fd = open(filename,O_RDWR | O_NONBLOCK);        //非阻塞访问
    if (fd < 0)
    {
        printf("file open failed\r\n");
        return -1;
    }


#if 0

    fds.fd = fd;
    fds.events = POLLIN;

    while (1)
    {
        ret_val = poll(&fds,1,500);

        if (ret_val)
        {
            ret_val = read(fd,&keyvalue,sizeof(keyvalue));
            if (ret_val < 0)
            {
                //读取错误
            }
            else
            {
                if (keyvalue)
                {
                    printf("keyvalue:%d\r\n",keyvalue);
                }
                
            }
            
        }
        else if (ret_val == 0)
        {
            //用户自定义超时处理
        }
        else if (ret_val < 0)
        {
            //错误处理
        }
    }
    
#else

    while (1)
    {
        FD_ZERO(&readfds);
        FD_SET(fd,&readfds);

        timeout.tv_sec = 0;
        timeout.tv_usec = 500000;

        ret_val = select(fd+1,&readfds,NULL,NULL,&timeout);

        switch (ret_val)
        {
        case 0:
            //自定义超时处理
            break;
        case -1:
            //自定义错误处理
            break;
        default:
            if (FD_ISSET(fd,&readfds))
            {
                printf("%d\r\n",ret_val);
                ret_val = read(fd,&keyvalue,sizeof(keyvalue));
                if (ret_val < 0)
                {
                    ///读取错误
                }
                else
                {
                    if (keyvalue)
                    {
                        printf("keyvalue:%d\r\n",keyvalue);
                    }
                    
                }
            }break;
        }
    }
    

#endif
    
    
    ret_val = close(fd);
    if (ret_val < 0)
    {
        printf("LED close failed\r\n");
        return -1;
    }
    
    return 0;
}